import tips from './tips.js'

const getUserInfo = (data, no) => {
	tips.login();
	uni.request({
		url: 'https://restaurant.lgdweb.com/api/login/login',
		data: data,
		header: {
			'Content-Type': 'application/x-www-form-urlencoded',
		},
		method: 'POST',
		success: res => {
			// console.log('getuser', res)
			uni.setStorageSync('user_id', res.data.data.user_id)
			uni.setStorageSync('nickname', res.data.data.nickname)
			uni.setStorageSync('portrait', res.data.data.portrait)
			no(res.data)
		},
		fail: err => {
			console.log('getuser--fail', err)
		},
		complete: () => {
			tips.hide()
		}
	})
}

const login = (no) => {
	uni.getUserProfile({
		'desc': '授权微信登录以完善用户信息',
		success: res => {
			let userInfo = {
				portrait: res.userInfo.avatarUrl,
				nickname: res.userInfo.nickName
			}
			uni.login({
				success: res => {
					userInfo.code = res.code;
					getUserInfo(userInfo, no)
				}
			})
		},
		fail: err => {
			console.log('getUserProfile--fail', err)
		}
	})
}

const getAuth = (no, yes) => {
	if (!uni.getStorageSync('user_id')) {  // 未登录
		uni.showModal({
			'title': '授权提示',
			'content': '授权微信登录以完善用户信息',
			success: res => {
				if (res.confirm) {
					// console.log('--auth')
					login(no)
				}
			}
		})
	} else {  // 已登录
		yes()
	}
}

export default {
	getAuth,
	login
}